AJAX - HTTP狀態碼


Posted by hoyi-23 on 2021-05-23


HTTP狀態碼指的就是圖中紅色區塊的數字。

以下會介紹最常見的兩種:

200

200 代表有順利取得,資料有正確回傳。

404

404 代表資料回傳錯誤。


let xhr = new XMLHttpRequest();
xhr.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);
xhr.send(null);
xhr.onload = function(){
    console.log(xhr.responseText);
    var str = JSON.parse(xhr.responseText);
    document.querySelector('.message').textContent = str[0].name;
}

我們也可以直接觀看xhr.status來查看是否載入正確。
或是寫成程式碼

let xhr = new XMLHttpRequest();
xhr.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);
xhr.send(null);
xhr.onload = function(){
    if(xhr.status == 200){
        var str = JSON.parse(xhr.responseText);
        document.querySelector('.message').textContent = str[0].name;
    }else{
        console.log('沒有正確載入!')
    }
}

CodePen範例練習


#ajax #Http狀態碼







Related Posts

[FE301] React 基礎(Class component 版):React 環境建置

[FE301] React 基礎(Class component 版):React 環境建置

如何在 CoderBridge 上撰寫文章?

如何在 CoderBridge 上撰寫文章?

Explore-Binary Search Tree

Explore-Binary Search Tree


Comments